import requests
import hashlib
import json
import time
from urllib.parse import urlencode, quote_plus


async def send_set_device_config(data):
    body = data['body']
    body["secret_id"] = "ff9ac18746d353f8b5624b26934126fac78b"
    body['timestamp'] = f'{int(time.time())}'
    sign = create_sign(body)
    try:
        # 发起 POST 请求（自动处理 JSON 序列化）
        response = requests.post(
            f'http://api.cloud.sz90.cn/index.php/adm{data["url"]}',
            json=body,  # 自动序列化为 JSON 并设置 Content-Type
            headers={"Content-Type": "application/json", "signature": sign},
            timeout=10 # 超时设置
        )

        # 检查 HTTP 状态码
        response.raise_for_status()

        # 解析响应 JSON
        result = response.json()
        result['imei'] = body['imei']
        print("响应数据：", json.dumps(result, indent=2))
        return result
    except requests.exceptions.HTTPError as errh:
        print(f"HTTP 错误：{errh}")
    except requests.exceptions.ConnectionError as errc:
        print(f"连接错误：{errc}")
    except requests.exceptions.Timeout as errt:
        print(f"超时错误：{errt}")
    except requests.exceptions.RequestException as err:
        print(f"请求异常：{err}")


def create_sign(data):
    secret_key = "pR3I5do/QfXxg6mKIaAtdw=="
    # 向我司服务器发送的JSON数据
    # 将JSON字符串转换为URL参数格式
    url_params = jsonToUrlParams(data) + secret_key
    # MD5加密
    return encrypt_to_md5(url_params)


def encrypt_to_md5(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()


def jsonToUrlParams(data):
    try:
        # 过滤非数字和字符串类型的值
        cleanedNode = {}
        for fieldName, fieldValue in data.items():
            if isinstance(fieldValue, (int, float, str)):
                cleanedNode[fieldName] = fieldValue

        # 对字段名进行排序
        sortedFields = sorted(cleanedNode.items())

        # 构建URL参数
        params = '&'.join([f"{k}={v}" for k, v in sortedFields])
        return params
    except Exception as e:
        print(e)
        return str(e)
